package com.lgt_enterprise_android.view.pages.me;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.services.core.PoiItem;
import com.bumptech.glide.Glide;
import com.lgt_enterprise_android.Constant;
import com.lgt_enterprise_android.R;
import com.lgt_enterprise_android.adapter.MyGridViewAdapter;
import com.lgt_enterprise_android.base.BaseActivity;
import com.lgt_enterprise_android.utils.BasicHttp;
import com.lgt_enterprise_android.utils.CommonUtil;
import com.lgt_enterprise_android.utils.HttpManager;
import com.lgt_enterprise_android.utils.OSSUtil;
import com.lgt_enterprise_android.utils.StringUtil;
import com.lgt_enterprise_android.view.dialogs.SelectPicDialog;
import com.lgt_enterprise_android.view.fragments.MeFragment;
import com.lgt_enterprise_android.view.pages.ImageLookingActivity;
import com.util.AppUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class EnterpriseActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private TextView txtInviteCode;
    private TextView txtEnterpriseName;
    private TextView txtShopName;
    private TextView txtShopAddress;
    private TextView txtName;

    private GridView mGridView;
    private MyGridViewAdapter mMyGridViewAdapter;

    private OSSUtil ossUtil;

    private String tenantId = "tmp";

    public static PoiItem currentPoiItme;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enterprise);
        initView();
        initData();
        bindEvent();
    }


    private void initView() {
        txtInviteCode = (TextView) findViewById(R.id.me_txt_inview_code);
        txtEnterpriseName = (TextView) findViewById(R.id.me_txt_enter_name);
        txtShopName = (TextView) findViewById(R.id.me_txt_shop_name);
        txtShopAddress = (TextView) findViewById(R.id.me_txt_shop_address);

        mGridView = (GridView) findViewById(R.id.gridview_imgs);
        txtName = (TextView) findViewById(R.id.me_txt_name);


    }

    private void initData() {
        findViewById(R.id.btn_ok).setVisibility(View.GONE);

        if (MeFragment.jsonEnterprise != null) {
            ImageView img = (ImageView) findViewById(R.id.me_img_head);
            Glide.with(this).applyDefaultRequestOptions(CommonUtil.getCircelGlideOptions()).load(MeFragment.jsonEnterprise.getJSONObject("organizationInfo").getString("logoUrl")).into(img);

            String strTitle = MeFragment.jsonEnterprise.getJSONObject("organizationInfo").getString("shortName");
            if (StringUtil.isEmpty(strTitle)) {
                strTitle = MeFragment.jsonProfileInfo.getString("phoneNumber");
            }
            txtName.setText(strTitle);
        }


        if (MeFragment.jsonEnterprise == null) {
            return;
        }

        JSONObject jsonOrg = MeFragment.jsonEnterprise.getJSONObject("organizationInfo");
        JSONObject jsonStore = MeFragment.jsonEnterprise.getJSONObject("storeInfo");

        if (jsonOrg == null || jsonStore == null) return;
        findViewById(R.id.btn_ok).setVisibility(View.VISIBLE);
        JSONArray jsonArrayImage = MeFragment.jsonEnterprise.getJSONArray("organizationImageDOList");

        if (jsonArrayImage != null) {
            ArrayList<String> listImages = new ArrayList<>();
            for (int i = 0; i < jsonArrayImage.size(); i++) {
                JSONObject jo = jsonArrayImage.getJSONObject(i);
                listImages.add(jo.getString("imageUrl"));
            }
            mMyGridViewAdapter = new MyGridViewAdapter(mContext, listImages);
            mGridView.setAdapter(mMyGridViewAdapter);

            if (listImages.size() > 2) {
                mGridView.getLayoutParams().height = (int) (AppUtil.getdensityDpi(mContext) * 220);
            }

        }

        tenantId = jsonOrg.getString("tenantId");

        txtEnterpriseName.setText(jsonOrg.getString("name"));

        txtShopName.setText(jsonStore.getString("name"));
        txtShopAddress.setText(jsonStore.getString("address"));
        txtInviteCode.setText(MeFragment.jsonEnterprise.getString("inviteCode"));

    }

    private void bindEvent() {
//        txtName.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Intent intent = new Intent(mContext, ProfileInfoActivity.class);
//                startActivity(intent);
//            }
//        });

        findViewById(R.id.lin_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, EditInfoActivity.class);
                intent.putExtra("type", EditInfoActivity.INVIEW_CODE);
                intent.putExtra("val", txtInviteCode.getText().toString());
                startActivityForResult(intent, EditInfoActivity.INVIEW_CODE);
            }
        });

        findViewById(R.id.lin_3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MeFragment.jsonEnterprise == null) {
                    showToast("未加入组织");
                } else {
                    Intent intent = new Intent(mContext, EditInfoActivity.class);
                    intent.putExtra("type", EditInfoActivity.SHOP_NAME);
                    intent.putExtra("val", txtShopName.getText().toString().trim());
                    startActivityForResult(intent, EditInfoActivity.SHOP_NAME);
                }
            }
        });

        findViewById(R.id.linAddress).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MeFragment.jsonEnterprise == null) {
                    showToast("未加入组织");
                } else {
                    Intent intent = new Intent(mContext, ShopAddressActivity.class);
                    String address = "";
                    if (MeFragment.jsonEnterprise != null) {
                        JSONObject jsonStore = MeFragment.jsonEnterprise.getJSONObject("storeInfo");
                        if (jsonStore != null && !StringUtil.isEmpty(jsonStore.getString("longitude")) && !StringUtil.isEmpty(jsonStore.getString("latitude"))) {
                            address = jsonStore.getString("longitude") + "#" + jsonStore.getString("latitude");
                        }
                    }
                    intent.putExtra("address", address);
                    startActivity(intent);
                }
            }
        });

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position != 5 && position == mMyGridViewAdapter.getCount() - 1) {
                    checkPermission();
                } else {
                    Intent intent = new Intent(mContext, ImageLookingActivity.class);
                    JSONArray jsonArray = new JSONArray();

                    for (String str : mMyGridViewAdapter.getList()) {
                        jsonArray.add(str);
                    }
                    intent.putExtra("imgsStr", jsonArray.toJSONString());
                    intent.putExtra(ImageLookingActivity.EXTRA_IMAGE_INDEX, position);
                    startActivity(intent);
                }
            }
        });


        findViewById(R.id.btn_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mMyGridViewAdapter == null) {
                    showToast("保存失败，请退出重新登录");
                    finish();
                    return;
                }

                int indexOfDiskImg = -1;

                ArrayList<String> listImg = mMyGridViewAdapter.getList();
                for (int i = 0; i < listImg.size(); i++) {
                    if (!listImg.get(i).startsWith("http")) {
                        indexOfDiskImg = i;
                        break;
                    }
                }

                if (indexOfDiskImg > -1) {
                    final int tmpStart = indexOfDiskImg;
                    showLoadingDialog();
                    HttpManager.getSTS(mContext, new BasicHttp.IMyCallBack() {
                        @Override
                        public void onResponse(final Object resonseObj) {
                            final JSONObject jo = (JSONObject) resonseObj;
                            ossUtil = new OSSUtil(mContext, jo.getString("accessKeyId"), jo.getString("accessKeySecret"), jo.getString("securityToken"), jo.getString("region"));
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    upload(jo, tmpStart);
                                }
                            }).start();

                        }

                        @Override
                        public void onFailure(String mes) {
                            dismissLoadingDialog();
                        }
                    });
                } else {
                    if (MeFragment.jsonEnterprise != null) {
                        postData();
                    }
                }
            }
        });
    }


    private void postData() {
        JSONObject jsonObject = new JSONObject();
        JSONObject joOrgUpdateRB = new JSONObject();

        if (currentPoiItme != null) {
            joOrgUpdateRB.put("latitude", currentPoiItme.getLatLonPoint().getLatitude());
            joOrgUpdateRB.put("longitude", currentPoiItme.getLatLonPoint().getLongitude());

            int tmp = Integer.parseInt(currentPoiItme.getAdCode());
            int cityCode = ((int) (tmp / 100)) * 100;
            int proviceCode = ((int) (tmp / 10000)) * 10000;
            joOrgUpdateRB.put("province", proviceCode);
            joOrgUpdateRB.put("city", cityCode);
            joOrgUpdateRB.put("area", currentPoiItme.getAdCode());
            joOrgUpdateRB.put("address", currentPoiItme.toString());
        }

        joOrgUpdateRB.put("name", txtShopName.getText().toString().trim());
        joOrgUpdateRB.put("id", MeFragment.jsonEnterprise.getJSONObject("storeInfo").getString("id"));
        joOrgUpdateRB.put("pid", MeFragment.jsonEnterprise.getJSONObject("storeInfo").getString("pid"));

        JSONArray jsonArrayImg = new JSONArray();
        for (int i = 0; i < mMyGridViewAdapter.getList().size(); i++) {
            JSONObject jo = new JSONObject();
            jo.put("imageUrl", mMyGridViewAdapter.getList().get(i));
            jsonArrayImg.add(jo);
        }

        jsonObject.put("orgUpdateRB", joOrgUpdateRB);
        jsonObject.put("organizationImageDTOList", jsonArrayImg);

        HttpManager.saveEnterPriseInfo(mContext, jsonObject.toJSONString(), new BasicHttp.IMyCallBack() {
            @Override
            public void onResponse(Object resonseObj) {
                dismissLoadingDialog();
                showToast("保存成功");
                finish();
            }

            @Override
            public void onFailure(String mes) {
                dismissLoadingDialog();
                showToast("信息保存失败");
            }
        });

    }

    private void upload(final JSONObject jo, final int index) {

        ossUtil.uploadFile(jo.getString("bucket"), jo.getString("folder") + "/" + tenantId + "/" + index + "_" + System.currentTimeMillis() + ".jpg", mMyGridViewAdapter.getItem(index), new OSSUtil.IOSSCallBack() {
            @Override
            public void onSuccess(String url) {
                mMyGridViewAdapter.getList().set(index, url);
                if (index == mMyGridViewAdapter.getList().size() - 1) {
                    postData();
                    return;
                }
                int tmpIndex = index;
                while (tmpIndex < 6) {
                    tmpIndex++;
                    if (!mMyGridViewAdapter.getList().get(tmpIndex).startsWith("http")) {
                        upload(jo, tmpIndex);
                    }
                }

                postData();
            }

            @Override
            public void onFailure(String mes) {
                showToast("图片上传失败");
                dismissLoadingDialog();
            }
        });


    }

    private void checkPermission() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            SelectPicDialog logoutDialog = new SelectPicDialog();
            logoutDialog.show(getSupportFragmentManager(), "SelectPicDialog");
        } else {
            EasyPermissions.requestPermissions(EnterpriseActivity.this, "请打开相机权限", 101, perms);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        txtShopAddress.setText(intent.getStringExtra("name"));
        txtShopAddress.setTag(intent.getStringExtra("location"));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == Constant.CAMERA_APP) {
            compress(Constant.mCamRequestedUri.getPath());
        } else if (requestCode == Constant.GALLERY_APP) {
            compress(CommonUtil.getRealPathFromURI(this, data.getData()));
        } else if (EditInfoActivity.INVIEW_CODE == requestCode) {
            txtInviteCode.setText(data.getStringExtra("val"));
        } else if (EditInfoActivity.ENTERPRISE_NAME == requestCode) {
            txtEnterpriseName.setText(data.getStringExtra("val"));
        } else if (EditInfoActivity.SHOP_NAME == requestCode) {
            txtShopName.setText(data.getStringExtra("val"));
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        //省略switch requestCode
        SelectPicDialog logoutDialog = new SelectPicDialog();
        logoutDialog.show(getSupportFragmentManager(), "SelectPicDialog");
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    private void compress(String path) {
        Luban.with(this)
                .load(path)
                .ignoreBy(100)
                .setTargetDir(getExternalCacheDir().getAbsolutePath())
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
//                        Log.i("cccccc","onStart");
                    }

                    @Override
                    public void onSuccess(File file) {
                        mMyGridViewAdapter.addPic(file.getAbsolutePath());
                        if (mMyGridViewAdapter.getCount() > 3) {
                            if (mGridView.getLayoutParams().height != (int) (AppUtil.getdensityDpi(mContext) * 220)) {
                                mGridView.getLayoutParams().height = (int) (AppUtil.getdensityDpi(mContext) * 220);
                            }
                        }
                        mMyGridViewAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {
                        //Log.i("cccccc","onError"+e.getLocalizedMessage());
                    }
                }).launch();
    }

}
